//
//  LBSIndex1ViewController.m
//  LBSYunDemo
//
//  Created by RetVal on 3/24/13.
//  Copyright (c) 2013 RetVal. All rights reserved.
//

#import "LBSIndex1ViewController.h"
#import "LBSWebViewController.h"
#import "iToast.h"
#import "LBSRequestManager.h"
#import "LBSRental.h"
#import "LBSRequest+LBSSearchRegion.h"
#import "LBSRequest+LBSSearchNearby.h"
#import "LBSDataCenter.h"
#import "LBSDataBase.h"
#import "LBSSharedData.h"
#import "Constants.h"
#import "BMapKit.h"
#import <CoreLocation/CoreLocation.h>
#import "BMKLocationComponent.h"

@interface RouteAnnotation : BMKPointAnnotation
{
	int _type; ///<0:起点 1：终点 2：公交 3：地铁 4:驾乘
	int _degree;
}

@property (nonatomic) int type;
@property (nonatomic) int degree;
@end

@implementation RouteAnnotation

@synthesize type = _type;
@synthesize degree = _degree;
@end


@interface LBSLocationAnnotation : NSObject<BMKAnnotation>
{
    LBSRental *_rental;
}
@property (strong, nonatomic) LBSRental *rental;
- (id)initWithRental:(LBSRental *)rental;
- (CLLocationCoordinate2D)coordinate;
- (NSString *)title;
- (NSString *)subtitle;
@end

@implementation LBSLocationAnnotation
- (id)initWithRental:(LBSRental *)rental
{
	if (self = [super init])
	{
		_rental = rental;
	}
	return self;
}

- (NSString *)title
{
	return _rental.rentalName;
}

- (NSString *)subtitle
{
	return _rental.locationName;
}

- (CLLocationCoordinate2D)coordinate
{
	return _rental.coordinate;
}
@end

@interface LBSIndex1ViewController ()<BMKMapViewDelegate, BMKRouteSearchDelegate, BMKLocationServiceDelegate,UIPickerViewDataSource, UIPickerViewDelegate>
{
    BMKMapView *_mapView;
    BMKRouteSearch* _routesearch;
    LBSLocationAnnotation *_selectedAnnotation;
    
    BMKPolyline* _polyLine;
    UIPickerView *_pickerView;
	NSUInteger _pickerRegionIndex;
	NSUInteger _pickerRentalIndex;
	NSUInteger _pickerPriceIndex;
	NSUInteger _pickerLocationIndex;
	NSUInteger _currentIndex;
    BOOL _tabBarHidden;
	BOOL _isLocationBasedSearch;
	BOOL _loading;
}
@property (weak, nonatomic) IBOutlet UIBarButtonItem *searchBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *nearBtn;
@property (assign, nonatomic) BOOL tabBarHidden;
@property (strong, nonatomic) UIPickerView *pickerView;
@property (assign, atomic) NSUInteger pickerRegionIndex;
@property (assign, atomic) NSUInteger pickerRentalIndex;
@property (assign, atomic) NSUInteger pickerPriceIndex;
@property (assign, atomic) NSUInteger pickerLocationIndex;
@property (assign, atomic) NSUInteger currentIndex;
@property (assign, atomic) BOOL userPickerChanged;
@property (assign, atomic) BOOL isLocationBasedSearch;
@property (assign, atomic) BOOL loading;
@property (strong, nonatomic) BMKMapView *mapView;
@property (strong, nonatomic) NSMutableArray *listContent;
@property (strong, nonatomic) LBSLocationAnnotation *selectedAnnotation;
@end

@implementation LBSIndex1ViewController{
    BMKLocationService *locService;
    BMKUserLocation *location;
    

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    if ([[UIScreen mainScreen] bounds].size.height == 568) {
        _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 458)];
    }else {
        _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 370)];
    }
    
    [self.view addSubview:_mapView];
	[self.mapView setDelegate:self];
    
    
    
    
    //定位功能
    
	[self.mapView setShowsUserLocation:YES];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    //[BMKLocationServicesetLocationDistanceFilter:100.f];
    //初始化BMKLocationService
    locService = [[BMKLocationService alloc]init];
    locService.delegate = self;
    //启动LocationService
    [locService startUserLocationService];
    
    
    
    
    _routesearch = [[BMKRouteSearch alloc]init];
    _routesearch.delegate = self;
	
	// setup UI title
	self.navigationItem.title = NSLocalizedString(LBSUIIndex1Title, nil);
    self.navigationController.navigationBar.translucent = NO;
	
	_pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 485, 320, 216)];
	[self.view addSubview:_pickerView];
	_pickerView.showsSelectionIndicator = YES;
	_pickerView.dataSource = self;
	_pickerView.delegate = self;
    
    
    //_________________
}

- (void)loadAnnotationWithArray:(NSArray *)information
{
	if (information == nil) return;
	NSArray *retainedInforation = information;
	dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
		NSMutableArray *annotations = [[NSMutableArray alloc] initWithCapacity:[retainedInforation count]];
		for (LBSRental *rental in retainedInforation) {
			LBSLocationAnnotation *locationAnnotation = [[LBSLocationAnnotation alloc] initWithRental:rental];
			[annotations addObject:locationAnnotation];
		}
		dispatch_async(dispatch_get_main_queue(), ^{
			[self.mapView addAnnotations:annotations];
		});
	});
	
}

- (void)viewDidUnload
{
	[self.mapView setShowsUserLocation:NO];
	[self setSearchBtn:nil];
	[self setNearBtn:nil];
	[super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
	LBSSharedData *data = [LBSSharedData sharedData];
	self.pickerRegionIndex = data.regionIdx;
	self.pickerPriceIndex = data.priceRangeIdx;
	self.pickerRentalIndex = data.rentalTypeIdx;
	self.pickerLocationIndex = data.locationTypeIdx;
	_listContent = [[LBSSharedData sharedData] lastResult] ?: _listContent;
	[self.mapView setShowsUserLocation:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
	if (_listContent) [[LBSSharedData sharedData] setResult:_listContent];
}

- (void)viewDidAppear:(BOOL)animated
{
	self.listContent = [[LBSSharedData sharedData] lastResult];
	if (self.listContent == nil) return;
	NSArray * array = [NSArray arrayWithArray:[self.mapView annotations]];
	[self.mapView removeAnnotations:array];
	[self loadAnnotationWithArray:self.listContent];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[self.mapView setShowsUserLocation:NO];
}

- (void)mapViewDidStopLocatingUser:(BMKMapView *)mapView
{
	NSLog(@"%@", NSStringFromSelector(_cmd));
	return;
}


#pragma mark -
#pragma mark 定位 BMKLocationServiceDelegate
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //NSLog(@"heading is %@",userLocation.heading);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    location=userLocation;
    //NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
}

#pragma mark -
#pragma mark UI Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
	if ([segue.identifier isEqualToString:@"segueForWebView"] == YES)
    {
		LBSWebViewController *webViewController = segue.destinationViewController;
		LBSRental *rental = self.selectedAnnotation.rental;
		webViewController.rental = rental;
    }
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    LBSLocationAnnotation *locationAnnotation = view.annotation;
    if ([locationAnnotation isKindOfClass:[LBSLocationAnnotation class]])
    {
        self.selectedAnnotation = locationAnnotation;
    }
        
    CLLocationCoordinate2D startPt = (CLLocationCoordinate2D){location.location.coordinate.latitude, location.location.coordinate.longitude};
    CLLocationCoordinate2D endPt = (CLLocationCoordinate2D){self.selectedAnnotation.rental.coordinate.latitude, self.selectedAnnotation.rental.coordinate.longitude};
    //反地理编码
//    BOOL f = [_search reverseGeocode:endPt];

    BMKPlanNode *start = [[BMKPlanNode alloc] init];
    start.pt = startPt;
    start.name = nil;
    
    BMKPlanNode *end = [[BMKPlanNode alloc] init];
    end.pt = endPt;
    end.name = nil;
    
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = start;
    drivingRouteSearchOption.to = end;
    BOOL flag = [_routesearch drivingSearch:drivingRouteSearchOption];
    if(flag)
    {
        NSLog(@"car检索发送成功");
    }
    else
    {
        NSLog(@"car检索发送失败");
    }

    
	
}

//- (void)onGetAddrResult:(BMKAddrInfo*)result errorCode:(int)error
//{
//    NSLog(@"%@",result.strAddr);
//}
- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        // 计算路线方案中的路段数目
        int size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"起点";
                item.type = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
                
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"终点";
                item.type = 1;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [_mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 添加途经点
        if (plan.wayPoints) {
            for (BMKPlanNode* tempNode in plan.wayPoints) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                item.type = 5;
                item.title = tempNode.name;
                [_mapView addAnnotation:item];
            }
        }
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        [self mapViewFitPolyLine:polyLine];
    }
}



//根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [_mapView setVisibleMapRect:rect];
    _mapView.zoomLevel = _mapView.zoomLevel - 0.3;
}







//- (void)onGetDrivingRouteResult:(BMKPlanResult*)result errorCode:(int)error
//{
//	NSLog(@"onGetDrivingRouteResult:error:%d", error);
//	if (error == BMKErrorOk) {
//        if (_polyLine) {
//            [_mapView removeOverlay:_polyLine];
//        }
//        
//		BMKRoutePlan* plan = (BMKRoutePlan*)[result.plans objectAtIndex:0];
//		
//		int index = 0;
//		int size = [plan.routes count];
//		for (int i = 0; i < 1; i++) {
//			BMKRoute* route = [plan.routes objectAtIndex:i];
//			for (int j = 0; j < route.pointsCount; j++) {
//				int len = [route getPointsNum:j];
//				index += len;
//			}
//		}
//        
//		BMKMapPoint* points = new BMKMapPoint[index];
//		index = 0;
//		
//		for (int i = 0; i < 1; i++) {
//			BMKRoute* route = [plan.routes objectAtIndex:i];
//			for (int j = 0; j < route.pointsCount; j++) {
//				int len = [route getPointsNum:j];
//				BMKMapPoint* pointArray = (BMKMapPoint*)[route getPoints:j];
//				memcpy(points + index, pointArray, len * sizeof(BMKMapPoint));
//				index += len;
//			}
//			size = route.steps.count;
//			
//		}
//		_polyLine = [BMKPolyline polylineWithPoints:points count:index];
//		[_mapView addOverlay:_polyLine];
//		delete []points;
//	}
//}

- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay{
    if ([overlay isKindOfClass:[BMKPolyline class]]){
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:1];
        polylineView.lineWidth = 5.0;
        return polylineView;
    }
    return nil;
}

- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view
{
    
	LBSLocationAnnotation *locationAnnotation = view.annotation;
    if ([locationAnnotation isKindOfClass:[LBSLocationAnnotation class]])
    {
        self.selectedAnnotation = locationAnnotation;
        [self performSegueWithIdentifier:@"segueForWebView" sender:self];
    }
}

- (void)stopLoading
{
	self.loading = NO;
}

- (void)loadMoreData
{
	if (self.loading) return;
	self.loading = YES;
	[iToast make:@"加载中..." duration:1000000];
	if (self.isLocationBasedSearch)
	{
		NSUInteger radius = 100000000;
		NSString *locationTag = nil;
		locationTag = [[[LBSDataBase sharedInstance] nearbyRadius] objectAtIndex:self.pickerLocationIndex];
		if ([locationTag isEqualToString:@"附近1000米"])
			radius = 1000;
        else if ([locationTag isEqualToString:@"附近3000米"])
			radius = 3000;
		else if ([locationTag isEqualToString:@"附近5000米"])
		    radius = 5000;
        else if ([locationTag isEqualToString:@"附近5000米"])
		    radius = 5000;
        else if ([locationTag isEqualToString:@"10公里以内"])
		    radius = 10000;
        else if ([locationTag isEqualToString:@"30公里以内"])
		    radius = 30000;
        else if ([locationTag isEqualToString:@"50公里以内"])
		    radius = 50000;
        else if ([locationTag isEqualToString:@"100公里以内"])
		    radius = 100000;
        else
		    radius = 100000000;
        
		[[LBSRequestManager defaultManager] addRequest:[[LBSRequest alloc] initWithURL:[NSURL URLWithString:kLBSRequestUpdateLocation]] locationUpdateComplete:^(CLLocation *location) {
			if (location)
			{
				[[LBSSharedData sharedData] setCurrentCoordinate2D:location.coordinate];
				[[LBSDataCenter defaultCenter] loadDataWithNearby:location.coordinate radius:radius index:[[LBSSharedData sharedData] currentIndex] pageSize:[[LBSSharedData sharedData] currentPageSize] pieceComplete:^(LBSRequest *request, id dataModel) {
					if (dataModel)
					{
						LBSRental *rental = [[LBSRental alloc] initWithDataModel:dataModel];
						LBSLocationAnnotation *locationAnnotation = [[LBSLocationAnnotation alloc] initWithRental:rental];
						[_listContent addObject:rental];
						[self.mapView addAnnotation:locationAnnotation];
					}
					else
					{
						if (request.error)
							[iToast make:LBSUINetWorkError duration:750];
						else if (request.availableItemCount)
							[iToast make:LBSUIDataComplete duration:750];
						else
							[iToast make:LBSUINoMoreData duration:750];
						[self performSelector:@selector(stopLoading) withObject:nil afterDelay:0.5];
					}
				}];
			}
			else
			{
				[iToast make:@"定位失败:(" duration:750];
				NSLog(@"reload data now.");
				[self performSelector:@selector(stopLoading) withObject:nil afterDelay:0.5];
			}
		}];
		[self performSelector:@selector(stopLoading) withObject:nil afterDelay:0.5];
		return;
	}
	NSRange priceRange = {0,0};
	if (self.pickerPriceIndex)
	{
		NSArray * names = [[LBSDataBase sharedInstance] priceRanges];
		NSString * priceTag = nil;
		priceTag = [names objectAtIndex:self.pickerPriceIndex];
		if ([priceTag isEqualToString:@"5千人以下"])
			priceRange = NSMakeRange(0, 5000);
		else if ([priceTag isEqualToString:@"5千-1万人"])
			priceRange = NSMakeRange(5000, 10000);
		else if ([priceTag isEqualToString:@"1万-2万人"])
			priceRange = NSMakeRange(10000, 20000);
		else if ([priceTag isEqualToString:@"2万-5万人"])
			priceRange = NSMakeRange(20000, 50000);
		else if ([priceTag isEqualToString:@"5万-10万人"])
			priceRange = NSMakeRange(50000, 100000);
		else if ([priceTag isEqualToString:@"10万-20万人"])
			priceRange = NSMakeRange(100000, 200000);
		else if ([priceTag isEqualToString:@"20万人以上"])
			priceRange = NSMakeRange(200000, 99999999);
	}
	[[LBSDataCenter defaultCenter] loadDataWithRegionName:[[[LBSDataBase sharedInstance] placeNames] objectAtIndex:self.pickerRegionIndex] priceRange:priceRange rentalType:self.pickerRentalIndex index:[[LBSSharedData sharedData] currentIndex] pageSize:[[LBSSharedData sharedData] currentPageSize] pieceComplete:^(LBSRequest *request, id dataModel) {
		if (dataModel)
		{
			LBSRental *rental = [[LBSRental alloc] initWithDataModel:dataModel];
			[_listContent addObject:rental];
			LBSLocationAnnotation *locationAnnotation = [[LBSLocationAnnotation alloc] initWithRental:rental];
			[self.mapView addAnnotation:locationAnnotation];
		}
		else
		{
			if (request.error)
				[iToast make:LBSUINetWorkError duration:750];
			else if (request.availableItemCount)
				[iToast make:LBSUIDataComplete duration:750];
			else
				[iToast make:LBSUINoMoreData duration:750];
			[self performSelector:@selector(stopLoading) withObject:nil afterDelay:0.5];
		}
	}];
	_currentIndex++;
}

- (void)reloadData
{
	_currentIndex = 0;
	NSArray *array = [NSArray arrayWithArray:_mapView.annotations];
	[_mapView removeAnnotations:array];
	[[LBSSharedData sharedData] setCurrentIndex:_currentIndex];
	[_listContent removeAllObjects];
	[self loadMoreData];
}
#pragma mark -
#pragma mark UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	if (self.isLocationBasedSearch) return 1;
	return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	if (component == 0)
	{
		if (self.isLocationBasedSearch)
		{
			return [[[LBSDataBase sharedInstance] nearbyRadius] count];
		}
		NSInteger cnt = 0;
		cnt = [[LBSDataBase sharedInstance] numberOfAllItems];
		if (cnt > 0) return cnt - 1;
		return cnt;
	}
	NSInteger idx = [pickerView selectedRowInComponent:0];
	if (idx != -1)
	{
		NSInteger cnt = 0;
		if (kLBSPlaceIndex == idx)
		{
			cnt = [[[LBSDataBase sharedInstance] placeNames] count];
		}
		else if (kLBSPriceIndex == idx)
		{
			cnt = [[[LBSDataBase sharedInstance] priceRanges] count];
		}
		else if (kLBSRentalIndex == idx)
		{
			cnt = [[[LBSDataBase sharedInstance] rentalTypes] count];
		}
		else if (kLBSNearbyIndex == idx)
		{
			cnt = [[[LBSDataBase sharedInstance] nearbyRadius] count];
		}
		return cnt;
	}
	return 0;
}

#pragma mark -
#pragma mark UIPickViewDelegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (_polyLine) {
        [_mapView removeOverlay:_polyLine];
    }
    
	self.userPickerChanged = YES;
	if (0 == component)
	{
		NSInteger idx = [pickerView selectedRowInComponent:component];
		if (-1 == idx) return;
		if (idx != -1 && !self.isLocationBasedSearch)
		{
			[_pickerView reloadComponent:1];
		}
		if (self.isLocationBasedSearch)
		{
			self.pickerLocationIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			return;
		}
		if (idx == 0)
			[self.pickerView selectRow:self.pickerRegionIndex inComponent:1 animated:YES];
		else if (idx == 1)
			[self.pickerView selectRow:self.pickerPriceIndex inComponent:1 animated:YES];
		else if (idx == 2)
			[self.pickerView selectRow:self.pickerRentalIndex inComponent:1 animated:YES];
	}
	else
	{
		NSInteger idx = [pickerView selectedRowInComponent:0];
		if (idx != -1)
		{
			if (kLBSPlaceIndex == idx)
			{
				self.pickerRegionIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			}
			else if (kLBSPriceIndex == idx)
			{
				self.pickerPriceIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			}
			else if (kLBSRentalIndex == idx)
			{
				self.pickerRentalIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			}
			else if (kLBSNearbyIndex == idx)
			{
				self.pickerLocationIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			}
		}
		
	}
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
	UILabel *myView = nil;
	if (component == 0)
	{
		if (self.isLocationBasedSearch)
		{
			myView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 280, 30)];
			myView.text = [[[LBSDataBase sharedInstance] nearbyRadius] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
		}
		else
		{
			myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)];
			myView.text = [[[LBSDataBase sharedInstance] itemsNames] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
		}
		
		// UITextAlignmnetCenter被iOS 6作为废弃定义了
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
		myView.textAlignment = NSTextAlignmentCenter;
#else
		myView.textAlignment = UITextAlignmentCenter;
#endif
		
		myView.font = [UIFont systemFontOfSize:14];//用label来设置字体大小
        
        
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE_7_0
//		myView.backgroundColor = [UIColor whiteColor];
//#else
        myView.backgroundColor = [UIColor clearColor];
//#endif
        
	}
	else
	{
		myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 180, 30)];
		// UITextAlignmentCenter被iOS 6作为废弃定义了
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
		myView.textAlignment = NSTextAlignmentCenter;
#else
		myView.textAlignment = UITextAlignmentCenter;
#endif
		NSInteger idx = [pickerView selectedRowInComponent:0];
		if (idx != -1)
		{
			//NSInteger cnt = 0;
			if (kLBSPlaceIndex == idx)
			{
				myView.text = [[[LBSDataBase sharedInstance] placeNames] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
			}
			else if (kLBSPriceIndex == idx)
			{
				myView.text = [[[LBSDataBase sharedInstance] priceRanges] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
			}
			else if (kLBSRentalIndex == idx)
			{
				myView.text = [[[LBSDataBase sharedInstance] rentalTypes] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
			}
		}
		myView.font = [UIFont systemFontOfSize:14];
        
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE_7_0
//		myView.backgroundColor = [UIColor whiteColor];
//#else
        myView.backgroundColor = [UIColor clearColor];
//#endif
	}
	
	return myView;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	CGFloat componentWidth = 0.0;
	if (self.isLocationBasedSearch)
	{
		return 280;
	}
	if (component == 0)
		componentWidth = 100.0; // 第一个组键的宽度
	else
		componentWidth = 180.0; // 第2个组键的宽度
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 60;
}


static void RSSetTabBarHidden(id context)
{
	LBSIndex1ViewController* self = context;
	for(UIView *view in self.tabBarController.view.subviews)
    {
		
		if([view isKindOfClass:[UITabBar class]])
        {
            if (self.tabBarHidden)
			{
                [view setFrame:CGRectMake(view.frame.origin.x,
										  view.frame.origin.y + view.frame.size.height,
										  view.frame.size.width,
										  view.frame.size.height)];
            }
			else
			{
                [view setFrame:CGRectMake(view.frame.origin.x,
										  view.frame.origin.y - view.frame.size.height,
										  view.frame.size.width,
										  view.frame.size.height)];
            }
        }
		else if ([view isKindOfClass:[BMKMapView class]])
		{
			NSLog(@"mapview");
		}
		else
        {
            if (self.tabBarHidden)
			{
                [view setFrame:CGRectMake(view.frame.origin.x,
										  view.frame.origin.y,
										  view.frame.size.width,
										  view.frame.size.height + (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) ? 49 : 0))];
            }
			else
			{
                [view setFrame:CGRectMake(view.frame.origin.x,
										  view.frame.origin.y,
										  view.frame.size.width,
										  view.frame.size.height - (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) ? 49 : 0))];
            }
        }
    }
}

- (void)popUpPickerView:(UIBarButtonItem *)sender
{
	[self.pickerView reloadAllComponents];
    self.pickerView.backgroundColor = [UIColor whiteColor];
	if ([sender.title isEqualToString:LBSUIBarBtnPlace] ||
		[sender.title isEqualToString:LBSUIBarBtnNear])
	{
		_searchBtn.title = @"确定";
		_searchBtn.enabled = NO;
		_nearBtn.enabled = NO;
		[UIView animateWithDuration:0.6 animations:^{
			[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			if ([[LBSDataCenter defaultCenter] isIphone5])
				self.pickerView.frame = CGRectMake(0, 288, 320, 216);
			else
				self.pickerView.frame = CGRectMake(0, 200, 320, 216);
			_tabBarHidden = YES;
			RSSetTabBarHidden(self);
		} completion:^(BOOL finished) {
			if (finished)
			{
				_searchBtn.enabled = YES;
				NSUInteger idx = [self.pickerView selectedRowInComponent:0];
				if (self.isLocationBasedSearch)
				{
					[self.pickerView selectRow:self.pickerLocationIndex inComponent:0 animated:YES];
				}
				else
				{
					if (idx == 0)
						[self.pickerView selectRow:self.pickerRegionIndex inComponent:1 animated:YES];
					else if (idx == 1)
						[self.pickerView selectRow:self.pickerPriceIndex inComponent:1 animated:YES];
					else if (idx == 2)
						[self.pickerView selectRow:self.pickerRentalIndex inComponent:1 animated:YES];
				}
			}
		}];
	}
	else if ([sender.title isEqualToString:@"确定"])
	{
		_searchBtn.title = LBSUIBarBtnPlace;
		_searchBtn.enabled = NO;
		[UIView animateWithDuration:0.6 animations:^{
			[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			self.pickerView.frame = CGRectMake(0, 480, 320, 216);
			_tabBarHidden = NO;
			RSSetTabBarHidden(self);
		} completion:^(BOOL finished) {
			if (finished)
			{
				if (self.userPickerChanged)
				{
					[[LBSSharedData sharedData] setRegionIdx:self.pickerRegionIndex];
					[[LBSSharedData sharedData] setPriceRangeIdx:self.pickerPriceIndex];
					[[LBSSharedData sharedData] setRentalTypeIdx:self.pickerRentalIndex];
					[[LBSSharedData sharedData] setLocationTypeIdx:self.pickerLocationIndex];
					[self reloadData];
					self.userPickerChanged = NO;
				}
				_searchBtn.enabled = YES;
				_nearBtn.enabled = YES;
			}
		}];
	}
}

- (IBAction)nearBtnPressed:(UIBarButtonItem *)sender
{
	_isLocationBasedSearch = YES;
	[self popUpPickerView:sender];
}

- (IBAction)searchBtnPressed:(UIBarButtonItem *)sender
{
	if (![sender.title isEqualToString:@"确定"])
		_isLocationBasedSearch = NO;
	[self popUpPickerView:sender];
}
@end
